package com.reggie.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reggie.common.ResultResponseVo;
import com.reggie.common.enums.front.LoginEnum;
import com.reggie.module.entity.po.User;
import com.reggie.module.mapper.UserMapper;
import com.reggie.module.service.MSMService;
import com.reggie.utils.CodeUtil;
import com.reggie.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.regex.Pattern;

import static com.reggie.common.Constant.*;

/**
 * @Author 早睡蛋
 * @Date 2022/9/26 21:01:25
 * @Desc:
 */
@Service
public class MSMServiceImpl implements MSMService {

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    private UserMapper userMapper;

    @Resource
    RedisUtil redisUtil;

    //验证码过期时间
    public final static Long msmExp = 60L;

    //邮箱发出者账号
    public final static String emailSender = "858162638@qq.com";

    /**
     * 获取验证码
     *
     * @param phone
     * @return
     */
    @Override
    public ResultResponseVo sendMsm(String phone) {
        boolean matchPhone = Pattern.matches(PHONE_REX, phone);
        if (!matchPhone) {
            return LoginEnum.PHONE_REX.getResultResponseVo();
        }
        String isPhone = redisUtil.getString(REGISTER_CODE + phone);
        if (isPhone != null) {
            return LoginEnum.MSM_EXIST.getResultResponseVo();
        }
        String code = CodeUtil.getCode();
        redisUtil.setStringExpire(REGISTER_CODE + phone, code, msmExp);
        return LoginEnum.SUCCESS.getResultResponseVo().setData(code);
    }


    /**
     * 发送邮箱验证码方法
     *
     * @param email
     * @param code
     */
    public void send(String email, String code) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("验证码");
        simpleMailMessage.setText("尊敬的用户，您的邮箱注册验证码为：   " + code + "     有效期为2分钟");
        simpleMailMessage.setTo(email);
        simpleMailMessage.setFrom(emailSender);
        javaMailSender.send(simpleMailMessage);
    }

}
